import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_member/stytle/listview_overScrollbehavior.dart';
import 'package:flutter_member/widget/loading_dialog.dart';
import 'package:flutter_member/widget/no_data.dart';
import 'package:flutter_member/widget/price_widget.dart';
import 'package:flutter_member/widget/universal_card.dart';
import 'package:flutter_member/widget/universal_card_item.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:toast/toast.dart';

///订单记录
class OrderRecordPage extends StatefulWidget {
  @override
  _OrderRecordPageState createState() => _OrderRecordPageState();
}

class _OrderRecordPageState extends State<OrderRecordPage> {
  // 一次加载5条数据
  int loadData = 2;

  // 加载中
  bool _loading = true;

  // 学费订单
  List<dynamic> _lstOrder = [];

  @override
  void initState() {
    _getTuitionOrder();
    super.initState();
  }
  /// 獲取學費訂單
  Future<void> _getTuitionOrder() async {
    final ParseUser user = await ParseUser.currentUser();
    var queryMem = QueryBuilder(ParseObject("Member"))
      ..whereEqualTo("objectId", user.get("member")["objectId"])
      ..includeObject(['student']);
    var repMem = await queryMem.query();
    if (repMem.results != null && repMem.success) {
      print(repMem.results);
      var query = QueryBuilder(ParseObject("TuitionOrder"))
        ..includeObject(['student','branch'])
        ..whereEqualTo("student", repMem.results.first["student"]);
      query.setLimit(loadData);
      var repOrder = await query.query();
      if (repOrder.results != null && repOrder.success) {
        setState(() {
          _loading=false;
          _lstOrder = repOrder.results.map((e)=>e).toList();
        });
      }else{
        if(loadData>5){
          Toast.show("沒有更多數據了", context,gravity:1 );
        }
        setState(()=>_loading=false);
      }
    }else{
      setState(()=>_loading=false);
    }
  }
  @override
  Widget build(BuildContext context) {
    //獲得屏幕的寬度
    final width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0Xff4d80c5),
        title: Text('訂單紀錄'),
      ),
      body: Center(
        child: Container(
          child: ScrollConfiguration(
              behavior: OverScrollBehavior(),
              child:_bodyWidget()
          ),
        ),
      ),
    );
  }
  /// 主要內容
  Widget _bodyWidget(){
    if(_loading==true){
      return CLoadingDialog(text: "加载中",);
    }else if(_lstOrder.length!=0){
      return EasyRefresh(
        header: PhoenixHeader(),
        footer: PhoenixFooter(),
        onRefresh:()async=> _getTuitionOrder,
        onLoad: ()async{
          setState(()=>loadData+=5);
          _getTuitionOrder();
        },
        child: Column(
          children: _lstOrder.map((e) => UniversalCard(title: e['studentName'], children: [
            UniversalCardItem(icon: "images/locations.png", title: e['branch']['address']),
            UniversalCardItem(icon: "images/payment.png", child: PriceWidget(realAmount: "${e['realAmount']}",amount: e['amount'],title2: "原價",),),
            UniversalCardItem(icon: "images/payment.png", child: PriceWidget(title:"已支付",realAmount: "${e['paid']}",amount: e["paidWait"],title2: "待支付",),),
            // UniversalCardItem(icon: "images/payment.png", title: "待支付 ${e['paidWait']}"),
          ],noImage: true,
              childRightWidget: _dataWidget(e["createdAt"])
          )).toList(),
        ),
      );
    }else{
      return NoDataWidget();
    }
  }
  /// widget 日期

  Widget _dataWidget(DateTime dateTime){
    return Container(
      child: Text(formatDate(dateTime, [yyyy,'-',mm,'-',dd])),
    );
  }
}
